package com.example.memorypoint.activity;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.LinearInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.example.memorypoint.DateBase.DiaryDatabase;
import com.example.memorypoint.R;
import com.example.memorypoint.adapter.DetailAdapter;
import com.example.memorypoint.utils.DesignDetailHelper;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.lxj.xpopup.XPopup;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import jp.wasabeef.richeditor.RichEditor;

public class WriteActivity extends AppCompatActivity implements View.OnClickListener {
    private static final int REQUEST_PICK_IMAGE = 1;
    public String TAG = "WriteActivity";
    public static final String EXTRA_DIARY_ID = "com.example.memorypoint.extra.DIARY_ID";
    public static final String EXTRA_DIARY_DATE = "com.example.memorypoint.extra.DIARY_DATE";
    private int diaryId;
    private EditText etTitle;
    private ImageButton btBack;
    private ImageButton btFinish;
    private ImageView emoji;
    private ImageView weather;
    private FloatingActionButton FontButton;
    private FloatingActionButton BackgroundButton;
    private FloatingActionButton PhotoButton;
    private FloatingActionButton musicButton;
    private String title;
    private String content;
    TextView textDate;
    String diaryDate;
    MediaPlayer mediaPlayer;
    ObjectAnimator rotationAnimator;
    RichEditor mEditor;
    String[] mPermissionList;
    // 保存选中的图片URI
    private Uri selectedImage;
    String wordCount;
    private TextView text_counts;
    private RelativeLayout rl_design_weatherAndEmoji;
    private int[] weathers = {R.drawable.ic_wether_bigheavilyrain, R.drawable.ic_wether_bigrain, R.drawable.ic_wether_bigsnow, R.drawable.ic_wether_cloudy, R.drawable.ic_wether_cold, R.drawable.ic_wether_dayrain, R.drawable.ic_wether_floatdust, R.drawable.ic_wether_foggy, R.drawable.ic_wether_freezingrain, R.drawable.ic_wether_heavilyrain, R.drawable.ic_wether_heavilysnow, R.drawable.ic_wether_lightrain, R.drawable.ic_wether_lightsnow, R.drawable.ic_wether_midrain, R.drawable.ic_wether_midsnow, R.drawable.ic_wether_nightcloudy, R.drawable.ic_wether_nightfoggy, R.drawable.ic_wether_nightrain, R.drawable.ic_wether_nightsnow, R.drawable.ic_wether_nightsun, R.drawable.ic_wether_rainsnow, R.drawable.ic_wether_sandblow, R.drawable.ic_wether_sandstorm, R.drawable.ic_wether_suddenrainsnow, R.drawable.ic_wether_suncloudy, R.drawable.ic_wether_sunfoggy, R.drawable.ic_wether_sunny, R.drawable.ic_wether_sunsnow, R.drawable.ic_wether_thunderrain, R.drawable.ic_wether_typhoon};
    private String[] weatherName = {"淋成落汤鸡", "好大的雨", "好大的雪", "阴天", "凉嗖的", "太阳雨", "浮尘", "看不清的一天", "冻雨", "暴雨", "暴雪", "小雨", "小雪", "中雨", "中雪", "夜间多云", "夜间大雾", "夜间下雨", "夜间下雪", "明朗的夜晚", "雨夹雪", "扬沙", "沙尘暴", "阵雨夹雪", "晴转多云", "晴天有雾", "晴朗", "太阳雪", "雷阵雨", "台风"};
    private ArrayList<DetailAdapter.Data> weatherResource = new ArrayList<>();
    private ArrayList<DetailAdapter.Data> emojiResource = new ArrayList<>();
    private int[] emojis = {R.drawable.ic_emoji_alien, R.drawable.ic_emoji_anger, R.drawable.ic_emoji_big_cry, R.drawable.ic_emoji_cry, R.drawable.ic_emoji_ghost, R.drawable.ic_emoji_giggle, R.drawable.ic_emoji_happy, R.drawable.ic_emoji_hurt, R.drawable.ic_emoji_joker, R.drawable.ic_emoji_laugh, R.drawable.ic_emoji_love, R.drawable.ic_emoji_null, R.drawable.ic_emoji_rhinorrhea, R.drawable.ic_emoji_sb, R.drawable.ic_emoji_scorn, R.drawable.ic_emoji_shit, R.drawable.ic_emoji_sleep, R.drawable.ic_emoji_small_love, R.drawable.ic_emoji_smile, R.drawable.ic_emoji_soclerver, R.drawable.ic_emoji_speechless, R.drawable.ic_emoji_star, R.drawable.ic_emoji_study, R.drawable.ic_emoji_vomit, R.drawable.ic_emoji_what};
    private String[] emojiName = {"外星人", "生气", "哭歪了", "笑麻了", "小鬼", "傻笑", "矜持的笑", "受伤", "小丑", "快乐", "傻白甜", "空集", "流鼻涕", "SB", "瞧不起你", "粑粑", "我要睡觉", "爱你", "笑", "假正经", "无语", "星星眼", "学习", "吐了", "纳尼",};
    private DiaryDatabase database = null;
    private boolean isContentModified = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 获取日记的id和date
        diaryId = getIntent().getIntExtra(EXTRA_DIARY_ID, 0);
        diaryDate = getIntent().getStringExtra(EXTRA_DIARY_DATE);

        Log.e("asd", "onCreate: "+diaryId);
        database = new DiaryDatabase(this.getBaseContext());

        setContentView(R.layout.activity_write);
        findViewById();
        initData();
        //初始化富文本编辑框
        initEditor();
        //进入写日记界面时先查询数据库检查该fragment是否有内容，根据传入的页面id查询
        initContent();
        //实时监控editText内容变化
        editWatcher();
        //音乐播放
        startMusic();

    }

    private void initData() {
        for (int info :
                weathers) {
            DetailAdapter.Data newInfo = new DetailAdapter.Data(getDrawable(info));
            weatherResource.add(newInfo);
        }
        for (int info :
                emojis) {
            DetailAdapter.Data newInfo = new DetailAdapter.Data(getDrawable(info));
            emojiResource.add(newInfo);
        }
    }


    public void findViewById() {
        etTitle = findViewById(R.id.title_text);
        btBack = findViewById(R.id.button_back);
        textDate = findViewById(R.id.date_text);
        btFinish = findViewById(R.id.finish);
        musicButton = findViewById(R.id.music);
        PhotoButton = findViewById(R.id.photo);
        emoji = findViewById(R.id.emoji);
        weather = findViewById(R.id.weather);
        text_counts = findViewById(R.id.text_counts);
        emoji.setOnClickListener(this);
        weather.setOnClickListener(this);
        musicButton.setOnClickListener(this);
        btFinish.setOnClickListener(this);
        btBack.setOnClickListener(this);
        PhotoButton.setOnClickListener(this);
        rl_design_weatherAndEmoji = findViewById(R.id.rl_design_weatherAndEmoji);
        rl_design_weatherAndEmoji.setOnClickListener(this);

    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.button_back) {
            if (isContentModified) {
                showSaveChangesDialog();
            } else
                finish(); // 结束当前Activity，避免重复返回
        } else if (id == R.id.finish) {
            saveContent();
            finish(); // 结束当前Activity，避免重复返回
        } else if (id == R.id.photo) {
            mEditor.focusEditor();
            ActivityCompat.requestPermissions(this, mPermissionList, 100);
        } else if (id == R.id.music) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                rotationAnimator.end();
            } else {
                mediaPlayer.start();
                startAnimation();
            }
        } else if (id == R.id.emoji) {

            new XPopup.Builder(this)
                    .autoOpenSoftInput(false)
                    .autoFocusEditText(false)
                    .moveUpToKeyboard(true) //如果不加这个，弹窗会移动到软键盘上面
                    .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                    .isThreeDrag(false) //是否开启三阶拖拽，如果设置enableDrag(false)则无效
                    .asCustom(new DesignDetailHelper(this, emojiResource, this, emojiName, "表情", diaryId, weather, emoji))
                    .show();
            Log.e(TAG, "onClick: "+this.diaryId );
        } else if (id == R.id.weather) {
            new XPopup.Builder(this)
                    .autoOpenSoftInput(false)
                    .autoFocusEditText(false)
                    .moveUpToKeyboard(true) //如果不加这个，弹窗会移动到软键盘上面
                    .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                    .isThreeDrag(false) //是否开启三阶拖拽，如果设置enableDrag(false)则无效
                    .asCustom(new DesignDetailHelper(this, weatherResource, this, weatherName, "天气", diaryId, weather, emoji))
                    .show();
        }
    }

    @SuppressLint("NonConstantResourceId")
    private void initEditor() {
        mPermissionList = new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE};
        mEditor = findViewById(R.id.editor);
        //初始化字体大小
        mEditor.setEditorFontSize(18);
        //初始化字体颜色
        mEditor.setEditorFontColor(Color.BLACK);
        //初始化内边距
        mEditor.setPadding(0, 12, 12, 12);
        //设置默认显示语句
        mEditor.setPlaceholder("请在这里留下你的心情...");
        mEditor.setTextColor(Color.BLACK);
        //设置编辑器是否可用
        mEditor.setInputEnabled(true);
        int[] buttonIds = {R.id.action_undo, R.id.action_redo, R.id.action_bold, R.id.action_italic, R.id.action_subscript, R.id.action_superscript, R.id.action_strikethrough, R.id.action_underline, R.id.action_heading1, R.id.action_heading2, R.id.action_heading3, R.id.action_heading4, R.id.action_heading5, R.id.action_heading6,};

        for (int buttonId : buttonIds) {
            findViewById(buttonId).setOnClickListener(v -> {
                if (buttonId == R.id.action_undo) {
                    mEditor.undo();
                } else if (buttonId == R.id.action_redo) {
                    mEditor.redo();
                } else if (buttonId == R.id.action_bold) {
                    mEditor.setBold();
                } else if (buttonId == R.id.action_italic) {
                    mEditor.setItalic();
                } else if (buttonId == R.id.action_subscript) {
                    mEditor.setSubscript();
                } else if (buttonId == R.id.action_superscript) {
                    mEditor.setSuperscript();
                } else if (buttonId == R.id.action_strikethrough) {
                    mEditor.setStrikeThrough();
                } else if (buttonId == R.id.action_underline) {
                    mEditor.setUnderline();
                } else if (buttonId == R.id.action_heading1) {
                    mEditor.setHeading(1);
                } else if (buttonId == R.id.action_heading2) {
                    mEditor.setHeading(2);
                } else if (buttonId == R.id.action_heading3) {
                    mEditor.setHeading(3);
                } else if (buttonId == R.id.action_heading4) {
                    mEditor.setHeading(4);
                } else if (buttonId == R.id.action_heading5) {
                    mEditor.setHeading(5);
                } else if (buttonId == R.id.action_heading6) {
                    mEditor.setHeading(6);
                }
            });
        }

        // 在 onCreate 方法中获取工具栏的引用
        HorizontalScrollView editorToolbar = findViewById(R.id.editor_toolbar);

        View rootView = findViewById(android.R.id.content);
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                rootView.getWindowVisibleDisplayFrame(r);
                int screenHeight = rootView.getRootView().getHeight();

                int keypadHeight = screenHeight - r.bottom;

                if (keypadHeight > screenHeight * 0.15) {
                    // 软键盘显示
                    // 在这里处理工具栏的逻辑
                    editorToolbar.setVisibility(View.VISIBLE);
                    musicButton.setVisibility(View.GONE);
                } else {
                    // 软键盘隐藏
                    // 在这里处理工具栏的逻辑
                    editorToolbar.setVisibility(View.GONE);
                    musicButton.setVisibility(View.VISIBLE);

                }
            }
        });


    }

    //播放音乐
    private void startMusic() {
        mediaPlayer = new MediaPlayer();
        AssetFileDescriptor afd = null;
        try {
            afd = getAssets().openFd("rain.mp3");
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            mediaPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //调用旋转动画
    private void startAnimation() {
        rotationAnimator = ObjectAnimator.ofFloat(musicButton, "rotation", 0f, 360f);
        rotationAnimator.setDuration(5000);
        rotationAnimator.setRepeatCount(ValueAnimator.INFINITE);
        rotationAnimator.setInterpolator(new LinearInterpolator());
        rotationAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                // 动画结束时执行的操作
            }
        });
        rotationAnimator.start();
    }


    //检查该fragment是否有内容,并初始化页面内容
    private void initContent() {
        String low = "-1";
        String emojiId = database.getEmojiById(diaryId);
        String weatherId = database.getWeatherById(diaryId);
        if (!emojiId.equals(low)&&!emojiId.equals("")){
            emoji.setImageDrawable(emojiResource.get(Integer.parseInt(emojiId)).getResource());
        }
        if (!weatherId.equals(low)&&!weatherId.equals("")){
            weather.setImageDrawable(weatherResource.get(Integer.parseInt(weatherId)).getResource());
        }

        //根据日记的id从数据库中读取日记的日期和标题
        textDate.setText(diaryDate);
        etTitle.setText(database.getTitleById(diaryId));
        content = database.getContentById(diaryId);
        mEditor.setHtml(content); // 设置编辑器的内容
        //初始化日记文字个数
        wordCount = calculateWordCount(content);
        text_counts.setText(wordCount);
        // 加载图片并设置到编辑器中
        if (selectedImage != null) {
            mEditor.focusEditor(); // 让 RichEditor 获取焦点
            mEditor.insertImage(selectedImage.toString(), "image"); // 插入图片
            selectedImage = null; // 清除保存的图片URI，避免重复加载
        }
    }

    //保存日记内容到数据库中
    private void saveContent() {
        title = etTitle.getText().toString();
        content = mEditor.getHtml(); // 获取编辑器中的内容
        database.updateDiary(diaryId, title, content);
    }

    //监听输入文本
    private void editWatcher() {
        etTitle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 在 EditText 内容变化前调用
                title = s.toString();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 在 EditText 内容变化时调用
                title = s.toString();
                // 获取最新的 EditText 内容
                Log.d(TAG, "onTextChanged:title " + title);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }

        });

        mEditor.setOnTextChangeListener(text -> {
            isContentModified = true;
            content = mEditor.getHtml(); // 获取编辑器中的内容
            wordCount = calculateWordCount(content);
            text_counts.setText(wordCount);
            Log.d(TAG, "onTextChange: " + content);
        });

    }

    //计算文字数量
    public String calculateWordCount(String input) {

        if (input == null || input.isEmpty()) {
            return "0";
        }
        int count = 0;
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            // 判断字符是否为中文字符
            if (isChineseCharacter(c)) {
                count++;
            }
        }
        return String.valueOf(count);
    }
    private boolean isChineseCharacter(char c) {
        Character.UnicodeBlock block = Character.UnicodeBlock.of(c);
        return block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || block == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || block == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || block == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT;
    }


    /**
     * 图片功能暂时有问题，先搁置
     */
    //选择图片
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_PICK_IMAGE) {
            selectedImage = data.getData();
            ContentResolver contentResolver = getContentResolver();
            try {
                InputStream inputStream = contentResolver.openInputStream(selectedImage);

                // 将输入流解码为Bitmap对象
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

                // 根据屏幕宽度和高度缩放Bitmap
                int screenWidth = getResources().getDisplayMetrics().widthPixels;
                int screenHeight = getResources().getDisplayMetrics().heightPixels;
                int bitmapWidth = bitmap.getWidth();
                int bitmapHeight = bitmap.getHeight();
                float scaleWidth = (float) screenWidth / bitmapWidth;
                float scaleHeight = (float) screenHeight / bitmapHeight;
                float scaleFactor = Math.min(scaleWidth, scaleHeight);
                Matrix matrix = new Matrix();
                matrix.postScale(scaleFactor, scaleFactor);
                Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, true);

                // 创建Drawable对象，并设置其边界
                Drawable drawable = new BitmapDrawable(getResources(), scaledBitmap);
                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());

                String imagePath = getFilePathFromUri(selectedImage); // 获取图片的本地文件路径
                mEditor.focusEditor(); // 让 RichEditor 获取焦点
                mEditor.insertImage(imagePath, "image"); // 插入图片

                // 隐藏软键盘
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(mEditor.getWindowToken(), 0);
            } catch (IOException e) {
                Log.e(TAG, "IOException", e);
            }
        }
    }

    // 获取文件的真实路径
    private String getFilePathFromUri(Uri uri) {
        String filePath = null;
        ContentResolver contentResolver = getContentResolver();
        Cursor cursor = null;
        try {
            cursor = contentResolver.query(uri, null, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                if (index != -1) {
                    String fileName = cursor.getString(index);
                    filePath = getFilesDir().getPath() + "/" + fileName;
                    Log.d(TAG, "File path: " + filePath);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Error getting file path from URI: " + e.getMessage());
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return filePath;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 100:
                boolean writeExternalStorage = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                boolean readExternalStorage = grantResults[1] == PackageManager.PERMISSION_GRANTED;
                if (writeExternalStorage && readExternalStorage) {
                    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.setType("image/*");
                    startActivityForResult(intent, REQUEST_PICK_IMAGE);
                } else {
                    Toast.makeText(this, "请设置必要权限", Toast.LENGTH_SHORT).show();
                }

                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (isContentModified) {
            showSaveChangesDialog();
        } else {
            super.onBackPressed();
        }
    }

    private void showSaveChangesDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("是否保存修改？");
        builder.setPositiveButton("保存", (dialog, which) -> {
            saveContent();

            finish();
        });
        builder.setNegativeButton("不保存", (dialog, which) -> finish());
        builder.show();
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
        if (rotationAnimator != null) {
            rotationAnimator.cancel();
            rotationAnimator = null;
        }
    }

    @Override
    public void onResume() {
        database.queryAllDiaries();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        database.close();
        super.onDestroy();
    }
}